package cn.vivi.seckill.service.impl;

import cn.vivi.seckill.exception.GlobalException;
import cn.vivi.seckill.mapper.OrderMapper;
import cn.vivi.seckill.pojo.*;
import cn.vivi.seckill.service.GoodsService;
import cn.vivi.seckill.service.OrderService;
import cn.vivi.seckill.service.SecKillGoodsService;
import cn.vivi.seckill.service.SecKillOrderService;
import cn.vivi.seckill.vo.GoodsVo;
import cn.vivi.seckill.vo.OrderVo;
import cn.vivi.seckill.vo.RespBean;
import cn.vivi.seckill.vo.RespBeanEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private SecKillGoodsService secKillGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SecKillOrderService secKillOrderService;

    /**
     * 去秒杀
     */
    @Override
    @Transactional // 一个事务
    public RespBean toSecKill(String goodsId, String userTicket, User user) {
        if (Objects.isNull(user)) {
            user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        }

        // 秒杀商品表库存减一
        SeckillGoods seckillGoods = secKillGoodsService.findByGoodsId(goodsId);
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        // 库存超卖
        int update = secKillGoodsService.updateStockCount(seckillGoods);
        if (update < 1) {
            // 更新失败
            return RespBean.error(RespBeanEnum.STOCK_NO_ENOUGH);
        }

        Goods goods = goodsService.findGoods(goodsId);

        if (seckillGoods.getStockCount() < 1) {
            // 设置该商品库存为空
            redisTemplate.opsForValue().set("isStockEmpty:" + goods.getId(), "0");

            return RespBean.error(RespBeanEnum.STOCK_NO_ENOUGH);
        }

        // 下订单
        Order order = new Order();
        order.setUserId(Long.parseLong(user.getPhone()));
        order.setGoodsId(Long.parseLong(goodsId));
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0); // 新建未支付
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        // 生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(Long.parseLong(user.getPhone()));
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        secKillOrderService.save(seckillOrder);

        //缓存秒杀订单
        redisTemplate.opsForValue().set("order:" + user.getPhone() + ":" + goodsId, seckillOrder);

        // 秒杀成功，返回订单
        return RespBean.success(order);
    }

    /**
     * 订单详情
     */
    @Override
    public OrderVo detail(String orderId) {
        Order order = orderMapper.selectById(orderId);
        if (StringUtils.isEmpty(orderId) || Objects.isNull(order)) {
            // 订单不存在
            throw new GlobalException(RespBeanEnum.ORDER_NO_EXIST);
        }
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId() + "");

        OrderVo orderVo = new OrderVo();
        orderVo.setOrder(order);
        orderVo.setGoodsVo(goodsVo);
        return orderVo;
    }


}
